package com.uplift.mgt.message.service.impl;

import com.github.pagehelper.PageHelper;
import com.uplift.common.Const;
import com.uplift.common.base.ServiceReslut;
import com.uplift.mgt.building.dao.RealtyFileMapper;
import com.uplift.mgt.building.model.RealtyFileModel;
import com.uplift.mgt.building.service.IRealtyFileService;
import com.uplift.mgt.customer.dao.CustomerMapper;
import com.uplift.mgt.message.dao.MessageMapper;
import com.uplift.mgt.message.model.MessageModel;
import com.uplift.mgt.message.service.IMessageService;
import com.uplift.sec.SecurityContext;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class MessageServiceImpl implements IMessageService {

	@Autowired
	private MessageMapper messageMapper;

	@Autowired
	private RealtyFileMapper realtyFileMapper;

	@Autowired
	private IRealtyFileService realtyFileService;

	@Override
	public List<Map<String, Object>> queryMessage(MessageModel messageModel) {
		PageHelper.startPage(messageModel.getPage(), messageModel.getLimit());
		return this.messageMapper.selectMessage(messageModel);
	}

	@Override
	public ServiceReslut addMessage(MessageModel messageModel) throws Exception {

		Map<String, Object> sessionUser = SecurityContext.getSessionUser();
		if(sessionUser == null) {
			return ServiceReslut.newServiceReslut(0, "获取登录用户信息失败");
		}

		messageModel.setMessageNum(generateNum());
		messageModel.setFromUserId((String) sessionUser.get("id"));
		messageModel.setFromUserName((String) sessionUser.get("name"));
		messageModel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		messageModel.setState("1");
		messageModel.setIsSure("0");		//默认消息为未确认
		messageModel.setCreateTime(new Date());

		if(messageModel.getFiles() != null) {
			String[] fileTypes = StringUtils.split(messageModel.getFileTypes(),",");
			if(fileTypes.length != messageModel.getFiles().length) {
				return ServiceReslut.newServiceReslut(0, "附件与附件类型不匹配。");
			}
			uploadMessageFile(messageModel);
		}

		return ServiceReslut.newServiceReslut(messageMapper.insertMessage(messageModel), "");
	}

	/**
	 * 生成消息编号
	 * @return
	 */
	private String generateNum() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
		return df.format(new Date());
	}

	/**
	 * 上传待办事项附件
	 * @param messageModel
	 */
	private void uploadMessageFile(MessageModel messageModel) throws Exception {
		String[] fileTypes = StringUtils.split(messageModel.getFileTypes(),",");
		CommonsMultipartFile cmf = null;
		String fileType = null;
		RealtyFileModel realtyFileModel = null;
		for (int i = 0; i < messageModel.getFiles().length; i++) {
			realtyFileModel = new RealtyFileModel();
			cmf = messageModel.getFiles()[i];
			fileType = fileTypes[i];

			FileItem item = cmf.getFileItem();
			String fileName = item.getName();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
			String newFilePath = "product/" + newFileName;
			File file = new File(Const.DIR_UPLOAD_BASE + newFilePath);
			item.write(file);
			// 设置图片路径
			realtyFileModel.setFilePath(newFilePath);
			realtyFileModel.setFileName(fileName);
			realtyFileModel.setBusiType(fileType);
			realtyFileModel.setRoomId(messageModel.getRoomId());
			realtyFileModel.setMessageId(messageModel.getId());
			realtyFileModel.setRoomNum(messageModel.getRoomNum());
			realtyFileModel.setRealtyId(messageModel.getRealtyId());
			realtyFileModel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			realtyFileModel.setCreateTime(new Date());
			realtyFileModel.setState("1");

			realtyFileMapper.insertRealtyFile(realtyFileModel);
		}
	}

	@Override
	public ServiceReslut updateMessage(MessageModel messageModel) throws Exception {
		if(messageModel.getFiles() != null) {
			String[] fileTypes = StringUtils.split(messageModel.getFileTypes(),",");
			if(fileTypes.length != messageModel.getFiles().length) {
				return ServiceReslut.newServiceReslut(0, "附件与附件类型不匹配。");
			}
			uploadMessageFile(messageModel);
		}

		deleteFiles(messageModel);		//删除相关文件
		messageModel.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(messageMapper.updateMessage(messageModel), "");
	}

	private void deleteFiles(MessageModel messageModel) {
		if(StringUtils.isNoneBlank(messageModel.getDelFiles())) {	//删除文件

			String[] deleteFiles = StringUtils.split(messageModel.getDelFiles(), ",");
			RealtyFileModel realtyFileModel = null;
			for (String deleteFile : deleteFiles) {
				realtyFileModel = new RealtyFileModel();
				realtyFileModel.setId(deleteFile);
				realtyFileService.deleteRealtyFile(realtyFileModel);
			}
		}
	}

	@Override
	public ServiceReslut deleteMessage(MessageModel messageModel) {
		messageModel.setState("0");		//删除状态
		messageModel.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(messageMapper.updateMessage(messageModel), "");
	}

	@Override
	public ServiceReslut sendMessage(MessageModel messageModel) {
		messageModel.setSendTime(new Date());
		messageModel.setUpdateTime(new Date());
		messageModel.setState("2");			//消息已发送
		return ServiceReslut.newServiceReslut(messageMapper.updateMessage(messageModel), "");
	}

	@Override
	public ServiceReslut rebackMessage(MessageModel messageModel) {
		messageModel.setSendTime(new Date());
		messageModel.setUpdateTime(new Date());
		messageModel.setState("1");			//消息撤回
		return ServiceReslut.newServiceReslut(messageMapper.updateMessage(messageModel), "");
	}

}
